<?php


namespace Mq\model;

use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Manager;

class BaseModel
{

    public static $_instance = null;
    public $db = null;
    public $tableName = '';
    public $dbName = 'admin';

    public function __construct()
    {

        $this->db = new Manager("mongodb://super:123456@localhost/" . $this->dbName . "?authSource=admin");


    }

    /**
     *  静态化类
     * @return null|static
     */
    public static function getInstance()
    {
        if (!isset(self::$_instance) || !(self::$_instance instanceof static)) {

            self::$_instance = new static;
        }
        return self::$_instance;
    }

    /**
     *  插入信息
     * @param $data
     * @return \MongoDB\Driver\WriteResult
     */
    public function insert($data)
    {
        $bulk = new BulkWrite;
        $bulk->insert($data);
        return $this->db->executeBulkWrite($this->dbName . "." . $this->tableName, $bulk);
    }

    /**
     * 修改操作
     * $bulk->update(
     *['x' => 2],
     *['$set' => ['y' => 3]],
     *['multi' => false, 'upsert' => false]
     *);
     * @param array $where
     * @param array $data
     * @param array $options
     * @return \MongoDB\Driver\WriteResult
     */
    public function update(array $where, array $data, array $options)
    {
        $bulk = new BulkWrite;
        if (empty($options)) {
            $bulk->update($where, $data);
        } else {
            $bulk->update($where, $data, $options);
        }
        return $this->db->executeBulkWrite($this->dbName . "." . $this->tableName, $bulk);
    }

    /**
     *  删除操作
     * $bulk->delete(['x' => 1], ['limit' => 1]);
     * @param $where
     * @param $options
     * @return \MongoDB\Driver\WriteResult
     */
    public function delete($where, $options)
    {
        $bulk = new BulkWrite;
        if (empty($options)) {
            $bulk->delete($where);
        } else {
            $bulk->delete($where, $options);
        }

        return $this->db->executeBulkWrite($this->dbName . "." . $this->tableName, $bulk);
    }
}